package com.trt.ecommerce.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author tanrentao
 * @date 2021-08-19
 * @desc HTTP请求头部携带Token验证过滤器(局部过滤器)
 * 参考PrefixPathGatewayFilterFactory， 本方法不在工厂里面写，分开写
 * 局部GatewayFilter
 * 全局GlobalFilter
 *
 * 实现局部过滤器
 * 1.实现GatewayFilter, Ordered
 * 2.加入到过滤器工厂里面，并将工厂注册到spring容器里面  HeaderTokenAbstractGatewayFilterFactory
 * 3.配置文件中心配置 （不配置，当前过滤器规则不被启用）
 */
public class HeaderTokenGatewayFilter implements GatewayFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 从 HTTP Header中寻找 key 为 token，value 为imooc 的键值对
        String name =exchange.getRequest().getHeaders().getFirst("token");
        if ("imooc".equals(name)) {
            return chain.filter(exchange);
        }

        // 标记此次请求没有权限,并结束这次请求
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE + 2; // HIGHEST_PRECEDENCE越大优先级越低
    }
}
